{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 程序编写方法(IPO)\n",
    "I :input  \n",
    "P :process  \n",
    "O :output  \n",
    "1.确定IPO  \n",
    "2.编写  \n",
    "3.调试  \n",
    "\n",
    "首先，掌握编程语法，熟悉基本概念和逻辑  \n",
    "其次，结合计算问题思考程序结构，会使用编程套路  \n",
    "最后，参照案例，多练习多实践，学会举一反三  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.基本数据类型及操作 for in \n",
    "\n",
    "整数：可正可负，没有大小限制  \n",
    "浮点数：取值范围和进度都存在限制，取值范围+-10^308,精度数量级10^-16  \n",
    "浮点数间运算存在不确定尾数，如：  \n",
    "0.1+0.2=0.30000000000000004  \n",
    "python用53位二进制表示小数部分，约e-16  \n",
    "0.1用二进制表示是无限小数  \n",
    "python提供复数类型  \n",
    "不同类型进行计算结果为最宽类型  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python 默认拥有以下内置数据类型：  \n",
    "  文本类型：\tstr  \n",
    "  数值类型：\tint, float, complex  \n",
    "  序列类型：\tlist, tuple, range  \n",
    "  映射类型：\tdict  \n",
    "  集合类型：\tset, frozenset  \n",
    "  布尔类型：\tbool  \n",
    "二进制类型：\tbytes, bytearray, memoryview  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "!a (使用 ascii()), !s (使用 str()) 和 !r (使用 repr()) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "%\t取模 - 返回除法的余数\tb % a 输出结果 1  \n",
    "**\t幂 - 返回x的y次幂\ta**b 为10的21次方  \n",
    "//\t取整除 - 向下取接近商的整数 -33//2=-17 33//2=-16  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 1234\n",
    "b = 'b'\n",
    "c = 'a+1'\n",
    "print(a, type(a))\n",
    "print(str(a), type(str(a)))\n",
    "print(repr(a), type(repr(a)))\n",
    "print(ord(b), type(ord(b)))\n",
    "print(ascii('å'), type(ascii('å')))  # 转义非 ASCII 字符\n",
    "print(hex(a), type(hex(a)))\n",
    "print(oct(a), type(oct(a)))\n",
    "print(c, type(c))\n",
    "print(eval(c), type(eval(c)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3.程序控制结构 \n",
    "# if elif else try except else finally break continue"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 异常处理\n",
    "try:\n",
    "    guss = eval(input())\n",
    "    print(\"猜{}了\".format(\"对\"if guss == 99 else \"错\"))\n",
    "except NameError:\n",
    "    print(\"格式错了\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# BMI_V1.py\n",
    "try:\n",
    "    height, weight = eval(input(\"请输入身高（米）和体重（千克）用逗号隔开：\"))\n",
    "    bmi = weight/pow(height, 2)\n",
    "    print(\"BMI数值为：{:.2f}\".format(bmi))\n",
    "    who, nat = \"\", \"\"\n",
    "    if bmi < 18.5:\n",
    "        who, nat = \"偏廋\", \"偏瘦\"\n",
    "    elif 18.5 <= bmi < 24:\n",
    "        who, nat = \"正常\", \"正常\"\n",
    "    elif 24 <= bmi < 25:\n",
    "        who, nat = \"正常\", \"偏胖\"\n",
    "    elif 25 <= bmi < 28:\n",
    "        who, nat = \"偏胖\", \"偏胖\"\n",
    "    elif 28 <= bmi < 30:\n",
    "        who, nat = \"偏胖\", \"肥胖\"\n",
    "    else:\n",
    "        who, nat = \"肥胖\", \"肥胖\"\n",
    "    print(\"WHO为{}，国内为{}\".format(who, nat))\n",
    "except: \n",
    "    print(\"请检查输入格式\")\n",
    "else: #正常退出（没有异常，break）执行\n",
    "    print(\"很好噢\")\n",
    "finally:\n",
    "    print(\"谢谢使用！\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for c in \"PYTHON\":\n",
    "    if c == \"T\":\n",
    "        continue\n",
    "    print(c, end=\"\")\n",
    "else:       # for 循环中的 else 关键字指定循环结束时要执行的代码块：\n",
    "    print(\"正常退出\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for c in \"PYTHON\":\n",
    "    if c == \"T\":\n",
    "        break\n",
    "    print(c, end=\"\")\n",
    "else:\n",
    "    print(\"正常退出\")  # 没有被break退出执行else"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# random库\n",
    "from import as def"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "random.seed(1)  # 产生种子\n",
    "\n",
    "print(random.random())  # 产生随机数\n",
    "print(random.randint(2, 3))  # 产生[a,b]的整数\n",
    "print(random.randrange(1, 100, 2))  # 产生[m,n)步长为K的整数\n",
    "print(random.getrandbits(6))  # 产生k比特长的整数\n",
    "print(random.uniform(1, 2))  # [a,b]随机小数\n",
    "print(random.choice([1, 2, 3, 4, 5, 6]))  # 序列seq中随机选一个元素\n",
    "\n",
    "# 随机排列seq\n",
    "ls = [1, 2, 3, 4, 5, 6]\n",
    "random.shuffle(ls)\n",
    "print(ls)  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 5函数的定义使用 递归\n",
    "# def return globle lambda True False not pass and or while"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# 可选参数\n",
    "def fact(n, m=1):\n",
    "    j = 1\n",
    "    for i in range(1, n+1):\n",
    "        j *= i\n",
    "    return j//m\n",
    "\n",
    "\n",
    "# 可变参数\n",
    "def fact2(n, *b):  # 可以是*c,*d\n",
    "    s = 1\n",
    "    for i in range(1, n+1):\n",
    "        s *= i\n",
    "    for item in b:\n",
    "        s *= item\n",
    "    return s\n",
    "\n",
    "\n",
    "print(fact(10))\n",
    "print(fact(10, 5))  # 位置对应\n",
    "print(fact(m=2, n=5))  # 名字对应\n",
    "print(fact2(2, 2, 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 局部变量为组合类型且未创建，等同于全局变量\n",
    "ls = [\"F\", 'f']\n",
    "\n",
    "\n",
    "def func(a):\n",
    "    ls.append(a)\n",
    "    return ls\n",
    "\n",
    "\n",
    "func(\"C\")\n",
    "print(ls)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 局部变量为组合类型且未创建，等同于全局变量\n",
    "ls = [\"F\", 'f']\n",
    "\n",
    "\n",
    "def func(a):\n",
    "    ls = []  # 真实创建\n",
    "    ls.append(a)\n",
    "    return ls\n",
    "\n",
    "\n",
    "func(\"C\")\n",
    "print(ls)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.组合数据类型\n",
    "集合 序列(基类类型):（元组，列表） 字典"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "序列类型（一维元素序列）（每个元素可以是不同类型）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "通用操作符  \n",
    "x in s  \n",
    "x not in s  \n",
    "s + t  \n",
    "s*n n*s  \n",
    "s[i]  \n",
    "s[i:j:k]  \n",
    "\n",
    "len(s)  \n",
    "min(s) max(s)  \n",
    "s.index(x) s.index(x,i,j)  \n",
    "s.count(x)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "列表类型（创建后可随意修改）  \n",
    "\n",
    "\n",
    "函数和方法  \n",
    "ls[i]=x  \n",
    "ls[i:j:K] = lt  \n",
    "del ls[i]  \n",
    "del ls[i:j:k]  \n",
    "ls += lt  \n",
    "ls *=n   \n",
    "ls.append(x)  \n",
    "ls.clear()  \n",
    "ls.copy()  \n",
    "ls.insert(i,x)  \n",
    "ls.pop(i)  \n",
    "ls.remove(x)  \n",
    "ls.reverse()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 真正创建一个列表\n",
    "creature = [\"cat\", \"dog\", \"tiger\", \"human\"]  \n",
    "print(creature)\n",
    "\n",
    "# 赋值仅传递引用，同一个列表有两个名字ls,creature\n",
    "ls = creature  \n",
    "print(ls)\n",
    "\n",
    "# 每一个字符变成list的元素\n",
    "ls = list(\"ilovepythone1234\")\n",
    "print(ls)\n",
    "\n",
    "# 切片\n",
    "lt = [\"@\", \"#\", \"$\"]\n",
    "ls[:5:2] = lt\n",
    "print(ls)\n",
    "\n",
    "# 复制\n",
    "ls *= 2\n",
    "print(ls)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表切片\n",
    "la = [1, 2, 3, 5]\n",
    "lb = la[::]     # 深复制\n",
    "lc = la         # 浅复制\n",
    "ld = [1, 2, 3, 5]\n",
    "\n",
    "print(id(la), \"\\t\", id(lb), \"\\t\", id(lc), \"\\t\", id(ld))\n",
    "print(la == lb, \"\\t\", la == lc)\n",
    "print(la is lb, \"\\t\", la is lc)\n",
    "la[3] = 4\n",
    "print(la, \"\\t\", lb, \"\\t\", lc)\n",
    "lc[3] = 3\n",
    "print(la, \"\\t\", lb, \"\\t\", lc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表自动内存管理功能\n",
    "x = [1, 2, 1, 2, 1, 1, 1]\n",
    "for i in x:\n",
    "    print(i)\n",
    "    if i == 1:\n",
    "        x.remove(i)\n",
    "        print(x)\n",
    "# 没有输出2，没有判断被移除元素的后一个\n",
    "# 元素自动向前收缩"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 列表自动内存管理功能\n",
    "x = [1, 2, 1, 2, 1, 1, 1]\n",
    "for i in x[::-1]:   # 从末尾向前\n",
    "    print(i)\n",
    "    if i == 1:\n",
    "        x.remove(i)\n",
    "        print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# list sort with lambda\n",
    "ls = [1, -2, 10, -12, -3, -5, -6, 8, 3, 7, 9]\n",
    "ls.sort(key=lambda x: (x < 0, abs(x)))\n",
    "print(ls)\n",
    "\n",
    "ls = [2, 412, 41, 5, 0, 3152, 613, 7, 48, 9, 4, 31]\n",
    "ls.sort()\n",
    "print(ls)\n",
    "ls.reverse()\n",
    "print(ls)\n",
    "ls.sort(reverse=True)\n",
    "print(ls)\n",
    "\n",
    "ls = [1, -2, 10, -12, -3, -5, -6, 8, 3, 7, 9]\n",
    "s = set(map(lambda x: x*x, ls))        # map()  返回迭代器\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lt = list()  # lt=[]\n",
    "lt = [1, 2, 3, 4, 5]  # lt += [1,2,3,4,5]\n",
    "lt[1] = \"@\"\n",
    "print(lt)\n",
    "lt.insert(1, '#')\n",
    "print(lt)\n",
    "del lt[0]\n",
    "print(lt)\n",
    "del lt[:3]\n",
    "print(lt)\n",
    "print(0 in lt)\n",
    "lt.append(0)\n",
    "print(lt.index(0))\n",
    "print(len(lt))\n",
    "print(max(lt))\n",
    "lt.clear()\n",
    "lt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 序列解包\n",
    "ls = [i for i in range(11)]\n",
    "print(*ls, sep=\"->\")\n",
    "\n",
    "ls = [1]\n",
    "ln = ['sdf']\n",
    "ll = {\"qwe\"}\n",
    "str = 'q'\n",
    "print(type(*str))\n",
    "print(*ls)\n",
    "print(type(ls),\n",
    "      type(*ls),\n",
    "      type(*ln),\n",
    "      type(ll),\n",
    "      type(*ll),\n",
    "      sep=\"\\t\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "集合操作  \n",
    "S | T  \n",
    "S - T  \n",
    "S & T  \n",
    "S <= T S < T  \n",
    "S >= T S > T  \n",
    "'''\n",
    "A = {\"python\", 123, (\"python\", 123)}  # 用{}建立集合\n",
    "B = set(\"pypy123\")  # 用set建立\n",
    "print(A)\n",
    "print(B)\n",
    "A |= B\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据去重\n",
    "ls = [\"p\", \"p\", \"y\", \"y\", 123, 1]\n",
    "s = set(ls)  # 集合无重复元素\n",
    "it = list(s)  # 将集合转换为列表\n",
    "print(it)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "字典类型 {} dict()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "函数和方法\n",
    "k in d  \n",
    "del d[k]  \n",
    "d.keys()  \n",
    "d.value()  \n",
    "d.item()  \n",
    "d.get(k,<default>)  \n",
    "d.pop(k,<default>)  \n",
    "d.popitem()  \n",
    "d.clear()  \n",
    "len(d)  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# dict\n",
    "d = {\"a\": 1, \"b\": \"2\", \"c\": 3, \"d\": 4, \"e\": 5}\n",
    "d[\"b\"] = 3\n",
    "print(len(d))\n",
    "del d[\"b\"]\n",
    "print(d.keys())\n",
    "print(d.values())\n",
    "print(d.items())\n",
    "print(\"a\" in d)\n",
    "print(\"b\" in d)\n",
    "print(d.get(\"a\", \"f\"))\n",
    "print(d.get(\"g\", \"f\"))\n",
    "print(d.pop(\"a\", \"f\"))\n",
    "print(d.pop(\"a\", \"f\"))\n",
    "print(d.popitem())\n",
    "d.clear"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 文件和数据格式化\n",
    "文件："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "f = open(filename,\"rwxabt+\")  \n",
    "f= open(\"hamlet.txt\")  \n",
    "f = open(\"hamlet.txt\",\"a+\")  \n",
    "\n",
    "f.read(size)  \n",
    "f.readline(size)  \n",
    "f.readlines(hint)  \n",
    "\n",
    "f.write(s)  \n",
    "f.writelines(list)  \n",
    "f.seek(offset)  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "fname = input(\"Enter file name:\")\n",
    "fo = open(fname, \"r\")\n",
    "txt = fo.read(2)\n",
    "while txt != \"\":\n",
    "    \"\"\" Process \"\"\"\n",
    "    txt = fo.read(2)\n",
    "fo.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "outputPrepend"
    ]
   },
   "outputs": [],
   "source": [
    "fname = input(\"Enter file name:\")\n",
    "fo = open(fname, \"r\")\n",
    "for line in fo.readlines():\n",
    "    \"\"\" Process \"\"\"\n",
    "fo.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fo = open(\"./txts/output.txt\", \"w+\")\n",
    "ls = [\"中国\", \"法国\", \"美国\", \"日本\", \"韩国\", \"朝鲜\"]\n",
    "fo.writelines(' '.join(ls))  # 将' '放到ls元素之间\n",
    "for line in fo:  # 从fo的当前位置，我们写过的信息在指针前面\n",
    "    print(line)  # 没有输出结果，因为文件指针在文件末尾\n",
    "fo.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fo = open(\"output.txt\", \"w+\")\n",
    "ls = [\"中国\", \"法国\", \"美国\"]\n",
    "fo.writelines(ls)\n",
    "fo.seek(0)\n",
    "for line in fo:\n",
    "    print(line)\n",
    "fo.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 一维数据：集合，列表(，元组，字典……)\n",
    "### 二维：由多个一维数据组成\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 从csv格式文件中读入数据\n",
    "fo = open(fname)\n",
    "ls = []\n",
    "for line in fo:\n",
    "    line = line.replace(\"\\n\", \"\")\n",
    "    ls.append(line.split(\",\"))\n",
    "fo.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将数据写入csv文件\n",
    "ls = [[], [], []]\n",
    "f = open(fname, \"w\")\n",
    "for item in ls:\n",
    "    f.write(','.join(item)+'\\n')\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 二维数据逐一处理\n",
    "ls = [[1, 2], [2, 3], [3, 4]]\n",
    "for row in ls:\n",
    "    for col in row:\n",
    "        print(col)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 程序设计方法学\n",
    "### 计算思维：抽象 + 自动化\n",
    "### 模拟XX过程 + 模拟N次\n",
    "### 自顶向下（设计） + 自底向上（执行（测试））"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# os库路径管理\n",
    "import os.path as op  # os库的子库（路径）\n",
    "fname = 'file'\n",
    "path = 'path'\n",
    "paths = []\n",
    "\n",
    "op.abspath(fname)  # 返回fname在当前系统中的绝对路径\n",
    "op.normpath(path)  # 归一化的path表示方式，用\\\\分隔\n",
    "op.relpath(path)  # 返回当前程序与文件之间的相对路径（relative path）\n",
    "\n",
    "op.dirname(path)  # 返回目录名\n",
    "op.basename(path)  # 返回path中最后的文件名\n",
    "op.join(path, *paths)  # 组合path与paths，返回一个路径字符串\n",
    "\n",
    "op.exists(path)  # 存在返回True，否则返回False\n",
    "op.isfile(path)\n",
    "op.isdir(path)\n",
    "\n",
    "op.getatime(path)  # 返回path对应文件或目录上一次访问的时间\n",
    "op.getmtime(path)  # 返回最近一次修改时间\n",
    "op.getctime(path)  # 返回创建时间\n",
    "\n",
    "op.getsize(path)  # 返回path对应文件的大小"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# os库进程管理\n",
    "import os\n",
    "os.system('command argument')  # 调用cmd命令，成功返回0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.system(\"calc.exe\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.system(\"mspaint.exe ./a.png\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# os库环境参数\n",
    "import os\n",
    "# os.chdir(path)#修改程序当前操作的路径\n",
    "os.getcwd()  # 返回当前操作路径\n",
    "# os.urandom(n)#获得n字节个长度的随机字符串，常用于加解密运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.urandom(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# BatchInstall\n",
    "import os\n",
    "libs = {\"requests\"}\n",
    "try:\n",
    "    for lib in libs:\n",
    "        os.system(\"pip install \" + lib)\n",
    "    print(\"Successful\")\n",
    "except:\n",
    "    print(\"Failed Somehow\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 查找 & 帮助\n",
    "# dir(random)                   # 查看模块中可用对象\n",
    "# help(random.randint)          # 查看指定方法的使用帮助\n",
    "# dir('')\n",
    "# dir(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# del不能删 元组、字符串 中指定元素，但是可以删除整个元组或字符串\n",
    "t1 = 1, 2, 3\n",
    "t2 = 4,\n",
    "t2 += t1\n",
    "# del t2[1]        TypeError: 'tuple' object doesn't support item deletion\n",
    "s1 = 'Tang Quanwei'\n",
    "# del s1[0]           TypeError: 'str' object doesn't support item deletion"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 输出重定向\n",
    "import sys\n",
    "fp = open(r'./test.txt', 'a+')\n",
    "print(sys.modules.items(), file=fp)\n",
    "fp.close"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ?:\n",
    "a = 1\n",
    "b = 2\n",
    "print(a if a > b else b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 根據一個序列的值对另一个序列进行过滤\n",
    "x = range(1, 20)\n",
    "y = (1, 0)*9+(1,)\n",
    "print(x, '\\n', y)\n",
    "list(itertools.compress(x, y))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 根据返回值分组\n",
    "def Size(v):\n",
    "    if v < 0:\n",
    "        return 'less than 0'\n",
    "    elif v < 10:\n",
    "        return 'between 0 and 10'\n",
    "    else:\n",
    "        return 'greater than 10'\n",
    "\n",
    "\n",
    "x = range(-10, 20)\n",
    "y = itertools.groupby(x, Size)\n",
    "for i, v in y:\n",
    "    print(type(i), type(v), type(y))\n",
    "    print(i, \":\", list(v))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def Say(message, times=2, length=10):\n",
    "    print((message+' ')*times)\n",
    "\n",
    "\n",
    "Say.__defaults__  # 查看default arguements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "split"
   },
   "outputs": [],
   "source": [
    "\"\"\" \n",
    "多次调用函数并且不为默认参数传值\n",
    "默认参数只在第一次调用时进行解释 \n",
    "\"\"\"\n",
    "\n",
    "\n",
    "def demo(newitem, old_list=[]):\n",
    "    old_list.append(newitem)\n",
    "    return old_list\n",
    "# after called, old_list stiall alive\n",
    "\n",
    "\n",
    "print(demo(1, [2, 3, 4, 5]))\n",
    "print(demo('a'))\n",
    "print(demo('bb'))\n",
    "print(demo(1, [2, 3, 4, 5]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "split"
   },
   "outputs": [],
   "source": [
    "def demo(newitem, old_list=[]):\n",
    "    if not old_list:\n",
    "        old_list = []\n",
    "    old_list.append(newitem)\n",
    "    return old_list\n",
    "\n",
    "\n",
    "print(demo(1, [2, 3, 4, 5]))\n",
    "print(demo('a'))\n",
    "print(demo('bb'))\n",
    "print(demo(1, [2, 3, 4, 5]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" 关键参数 \"\"\"\n",
    "demo(old_list=[1, 2, 3], newitem=88)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" 可变长度参数 \"\"\"\n",
    "\n",
    "\n",
    "def demo(**para):\n",
    "    for item in para.items():\n",
    "        print(item)\n",
    "    print(para)\n",
    "\n",
    "\n",
    "demo(x=1, y=2, z=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add(a, *b):\n",
    "    print(a+sum(b))\n",
    "    return\n",
    "\n",
    "\n",
    "ls = [i for i in range(101)]\n",
    "add(*ls)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import functools\n",
    "dir(functools)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" yield生成器 \"\"\"\n",
    "\n",
    "\n",
    "def f():\n",
    "    a, b = 1, 1\n",
    "    while True:\n",
    "        yield a\n",
    "        a, b = b, a+b\n",
    "\n",
    "\n",
    "a = f()\n",
    "for i in range(10):\n",
    "    print(a.__next__(), end=' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in f():\n",
    "    if i > 100:\n",
    "        break\n",
    "    print(i, end=' ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" 查看函数字节码 \"\"\"\n",
    "import dis\n",
    "dis.dis(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" 嵌套定义 \"\"\"\n",
    "\n",
    "\n",
    "def linear(a, b):\n",
    "    def result(x):\n",
    "        return a*x+b\n",
    "    return result\n",
    "\n",
    "\n",
    "taxes = linear(0.3, 2)\n",
    "taxes(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# global\n",
    "def a():\n",
    "    # global关键字用来在函数或其他局部作用域中使用全局变量。\n",
    "    # 但是如果不修改全局变量也可以不使用global关键字\n",
    "    print(global_)\n",
    "\n",
    "\n",
    "def b():\n",
    "    global global_\n",
    "    print(global_)\n",
    "    print(global_ := 1)\n",
    "\n",
    "\n",
    "global_ = 0\n",
    "# a()\n",
    "# b()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# nonlocal\n",
    "def make_counter():\n",
    "    count = 0\n",
    "\n",
    "    def counter():\n",
    "        nonlocal count\n",
    "        count += 1\n",
    "        return count\n",
    "    return counter\n",
    "\n",
    "\n",
    "def make_counter_test():\n",
    "    mc = make_counter()\n",
    "    print(mc())\n",
    "    print(mc())\n",
    "    print(mc())\n",
    "\n",
    "\n",
    "make_counter_test()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = \"global\"\n",
    "\n",
    "\n",
    "def foo():\n",
    "    x = \"foo\"\n",
    "\n",
    "    def bar():\n",
    "        # print(x)\n",
    "        nonlocal x\n",
    "        x = \"bar\"\n",
    "        print(x)\n",
    "    bar()\n",
    "\n",
    "\n",
    "foo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "center"
   },
   "outputs": [],
   "source": [
    "# 生成器\n",
    "gen = (i for i in range(-20, 21) if i % 2 == 0)\n",
    "for i in gen:\n",
    "    # print(i)\n",
    "    ...\n",
    "\n",
    "\n",
    "def fib(max):\n",
    "    n, a, b = 0, 0, 1\n",
    "    while n < max:\n",
    "        print(b)\n",
    "        a, b = b, a + b\n",
    "        n = n + 1\n",
    "    return 'done'\n",
    "\n",
    "# 一个函数定义中包含yield关键字，\n",
    "# 那么这个函数就不再是一个普通函数，而是一个generator\n",
    "\n",
    "\n",
    "def fib(max):\n",
    "    n, a, b = 0, 0, 1\n",
    "    while n < max:\n",
    "        yield b\n",
    "        a, b = b, a + b\n",
    "        n = n + 1\n",
    "    return 'done'\n",
    "\n",
    "\n",
    "# 如果想要拿到返回值，必须捕获StopIteration错误，\n",
    "# 返回值包含在StopIteration的value中\n",
    "g = fib(6)\n",
    "while True:\n",
    "    try:\n",
    "        x = next(g)\n",
    "        print('g:', x)\n",
    "    except StopIteration as e:\n",
    "        print('Generator return value:', e.value)\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 可以被next()函数调用并不断返回下一个值的对象称为迭代器：Iterator\n",
    "# 判断\n",
    "from collections.abc import Iterable\n",
    "from collections.abc import Iterator\n",
    "print(isinstance([], Iterable))\n",
    "print(isinstance((x for x in range(10)), Iterator))\n",
    "# 生成器都是Iterator对象，但list、dict、str虽然是Iterable，却不是Iterator\n",
    "print(isinstance([], Iterator))\n",
    "# 凡是可作用于for循环的对象都是Iterable类型\n",
    "# 凡是可作用于next()函数的对象都是Iterator类型\n",
    "# Python的for循环本质上就是通过不断调用next()函数实现的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from itertools import permutations\n",
    "from functools import reduce\n",
    "\n",
    "ls = permutations([1, 2, 3, 4])\n",
    "for i in ls:\n",
    "    print(reduce(lambda x, y: x*10+y, i))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ls = [1, 2, 3, 4, \":\", 5, 6, 7]\n",
    "\n",
    "\n",
    "def my_reverse(ls, n):\n",
    "    return ls[:n][::-1]+[ls[n]]+ls[n+1:][::-1]\n",
    "\n",
    "\n",
    "def my_reverse(ls, char):\n",
    "    idx = ls.index(char)\n",
    "    return ls[:idx][::-1]+[ls[idx]]+ls[idx+1:][::-1]\n",
    "\n",
    "\n",
    "print(my_reverse(ls, 2))\n",
    "print(my_reverse(ls, ':'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def _odd_iter():\n",
    "    n = 1\n",
    "    while True:\n",
    "        n += 2\n",
    "        yield n\n",
    "\n",
    "\n",
    "def primes():\n",
    "    yield 2\n",
    "    it = _odd_iter()  # 初始序列\n",
    "    while True:\n",
    "        n = next(it)  # 返回序列的第一个数\n",
    "        yield n\n",
    "        it = filter(lambda x: x % n != 0, it)  # 构造新序列\n",
    "\n",
    "\n",
    "for n in primes():\n",
    "    if n < 100:\n",
    "        print(n, end=' ')\n",
    "    else:\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 在代码运行期间动态增加功能的方式，称之为“装饰器”（Decorator）。\n",
    "# 本质上，decorator就是一个返回函数的高阶函数\n",
    "def log(func):\n",
    "    def wrapper(*names, **kw):\n",
    "        print('call %s():' % func.__name__)\n",
    "        return func(*names, **kw)\n",
    "    return wrapper\n",
    "\n",
    "# 借助Python的@语法，把decorator置于函数的定义处\n",
    "# 相当于 now = log(now)\n",
    "\n",
    "\n",
    "@log\n",
    "def now():\n",
    "    print(\"now 2021 5 12\")\n",
    "\n",
    "\n",
    "f = now\n",
    "f()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def log(text):\n",
    "    def decorator(func):\n",
    "        def wrapper(*names, **kw):\n",
    "            print('%s %s():' % (text, func.__name__))\n",
    "            return func(*names, **kw)\n",
    "        return wrapper\n",
    "    return decorator\n",
    "\n",
    "# now = log('execute')(now)\n",
    "\n",
    "\n",
    "@log('execute')\n",
    "def now():\n",
    "    print('2015-3-25')\n",
    "\n",
    "\n",
    "now()\n",
    "now.__name__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import functools\n",
    "import time\n",
    "\n",
    "\n",
    "def log(text):\n",
    "    def decorator(func):\n",
    "        @functools.wraps(func)\n",
    "        def wrapper(*names, **kw):\n",
    "            print('%s %s %s():' % (time.ctime(), text, func.__name__))\n",
    "            return func(*names, **kw)\n",
    "        return wrapper\n",
    "    return decorator\n",
    "\n",
    "\n",
    "@log('execute')\n",
    "def now():\n",
    "    print('2015-3-25')\n",
    "\n",
    "\n",
    "now()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 偏函数\n",
    "import functools\n",
    "int2 = functools.partial(int, base=2)\n",
    "int2('1000000')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from types import MethodType\n",
    "\n",
    "\n",
    "class MyCLass(object):\n",
    "    \"\"\"docstring for MyCLass.\"\"\"\n",
    "    # 只允许对Student实例添加name和age属性\n",
    "    __slots__ = ('__name', 'num', 'say', \"__scores\")  # 用tuple定义允许绑定的属性名称\n",
    "\n",
    "    def __init__(self, name, scores=0):\n",
    "        super(MyCLass, self).__init__()\n",
    "        self.__name = name\n",
    "        self.__scores = scores\n",
    "\n",
    "    # @property装饰器就是负责把一个方法变成属性调用的\n",
    "    @property\n",
    "    def getScores(self):\n",
    "        return self.__scores\n",
    "\n",
    "\n",
    "def say(self):\n",
    "    print(say.__name__, \"is running\")\n",
    "\n",
    "\n",
    "s = MyCLass(\"Ss\")\n",
    "\n",
    "# 给实例绑定一个属性\n",
    "s.num = \"1234\"\n",
    "\n",
    "# 给实例绑定一个方法,对另一个实例是不起作用的\n",
    "s.say = MethodType(say, s)\n",
    "s.say()\n",
    "\n",
    "# 给class绑定方法\n",
    "MyCLass.say = say\n",
    "\n",
    "s2 = MyCLass(\"asd\")\n",
    "s2.say()\n",
    "s2.getScores"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Fib(object):\n",
    "    def __init__(self, name=\"Fib\"):\n",
    "        self.a, self.b = 0, 1\n",
    "#         self.name = name\n",
    "        # 初始化两个计数器a，b\n",
    "\n",
    "#     def __str__(self):\n",
    "#         return f'Fib object (name:{self.name})'\n",
    "#     __repr__ = __str__\n",
    "\n",
    "#     def __call__(self):\n",
    "#         print('My name is %s.' % self.name)\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "        # 实例本身就是迭代对象，故返回自己\n",
    "\n",
    "    def __next__(self):\n",
    "        self.a, self.b = self.b, self.a + self.b  # 计算下一个值\n",
    "        if self.a > 100000:\n",
    "            # 退出循环的条件\n",
    "            raise StopIteration()\n",
    "        return self.a\n",
    "        # 返回下一个值\n",
    "\n",
    "    def __getitem__(self, n):\n",
    "        def __getitem__(self, n):\n",
    "            if isinstance(n, int):  # n是索引\n",
    "                a, b = 1, 1\n",
    "            for x in range(n):\n",
    "                a, b = b, a + b\n",
    "            return a\n",
    "        if isinstance(n, slice):  # n是切片\n",
    "            start = n.start\n",
    "            stop = n.stop\n",
    "            if start is None:\n",
    "                start = 0\n",
    "            a, b = 1, 1\n",
    "            L = []\n",
    "            for x in range(stop):\n",
    "                if x >= start:\n",
    "                    L.append(a)\n",
    "                a, b = b, a + b\n",
    "            return L\n",
    "\n",
    "\n",
    "Fib()[:3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 枚举类Enumerate class\n",
    "from enum import Enum\n",
    "# value属性则是自动赋给成员的int常量，默认从1开始计数\n",
    "Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May',\n",
    "             'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))\n",
    "for name, member in Month.__members__.items():\n",
    "    print(name, '=>', member, ',', member.value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from enum import Enum, unique\n",
    "\n",
    "\n",
    "@unique  # 装饰器可以帮助我们检查保证没有重复值。\n",
    "class Weekday(Enum):\n",
    "    Sun = 0  # Sun的value被设定为0\n",
    "    Mon = 1\n",
    "    Tue = 2\n",
    "    Wed = 3\n",
    "    Thu = 4\n",
    "    Fri = 5\n",
    "    Sat = 6\n",
    "\n",
    "\n",
    "for i in Weekday:\n",
    "    print(i)\n",
    "\n",
    "for name, member in Weekday.__members__.items():\n",
    "    print(name, '=>', member.value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# type()函数既可以返回一个对象的类型，又可以创建出新的类型\n",
    "def fn(self, name='word'):\n",
    "    print(\"Hello\", name)\n",
    "\n",
    "\n",
    "# 要创建一个class对象，type()函数依次传入3个参数：\n",
    "# class的名称；\n",
    "# 继承的父类集合，注意Python支持多重继承，如果只有一个父类，别忘了tuple的单元素写法；\n",
    "# class的方法名称与函数绑定，这里我们把函数fn绑定到方法名hello上。\n",
    "Hello = type('hello', (object,), dict(hello=fn))\n",
    "# 创建Hello class\n",
    "h = Hello()\n",
    "h.hello()\n",
    "print(type(Hello))\n",
    "print(type(h))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import namedtuple\n",
    "Point = namedtuple(\"point\", ['x', 'y'])\n",
    "p = Point(1, 2)\n",
    "print(p.x, p.y)\n",
    "print(isinstance(p, Point))\n",
    "print(isinstance(p, tuple))\n",
    "# help(namedtuple)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import deque\n",
    "# * 高效实现插入和删除操作的双向列表\n",
    "q = deque(['a', 'b', 'c'])\n",
    "q.append('x')\n",
    "print(q)\n",
    "q.appendleft('y')\n",
    "print(q)\n",
    "q.popleft()\n",
    "print(q)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Person():\n",
    "    def __init__(self, name, age, gender):\n",
    "        self.__name = name\n",
    "        self.__age = age\n",
    "        self.__gender = ['Error', gender][gender in ['Male', 'Female']]\n",
    "\n",
    "    @property\n",
    "    def personInfo(self):\n",
    "        print(\"name:\", self.__name, \"\\nage:\",\n",
    "              self.__age, \"\\ngender:\", self.__gender)\n",
    "\n",
    "    @property\n",
    "    def getName(self):\n",
    "        return self.__name\n",
    "\n",
    "    @property\n",
    "    def getAge(self):\n",
    "        return self.__age\n",
    "\n",
    "    @property\n",
    "    def getGender(self):\n",
    "        return self.__gender\n",
    "\n",
    "\n",
    "class Student(Person):\n",
    "    def __init__(self, name, age, gender, collage, class_):\n",
    "        super().__init__(name, age, gender)\n",
    "        self.__collage = collage\n",
    "        self.__class = class_\n",
    "\n",
    "    @property\n",
    "    def personInfo(self):\n",
    "        print(\"name:\", self.__name, \"\\nage:\", self.getAge, \"\\ngender:\",\n",
    "              self.getGender, \"\\ncollage:\", self.__collage, \"\\nclass:\", self.__class)\n",
    "\n",
    "    def study(self, teacher):\n",
    "        print(f\"{teacher.getName}老师,我终于学会了{teacher.teachObj}\")\n",
    "\n",
    "    def __str__(self):\n",
    "        return \"name:\" + self.getName + \"\\nage:\" + self.getAge + \"\\ngender:\" + self.getGender + \"\\ncollage:\" + self.__collage + \"\\nclass:\" + self.__class\n",
    "    __repr__ = __str__\n",
    "\n",
    "\n",
    "class Teacher(Person):\n",
    "    def __init__(self, name, age, gender, college, professional):\n",
    "        super().__init__(name, age, gender)\n",
    "        self.__collage = college\n",
    "        self.__professional = professional\n",
    "\n",
    "    @property\n",
    "    def personInfo(self):\n",
    "        print(\"name:\", self.getName, \"\\nage:\", self.getAge, \"\\ngender:\", self.getGender,\n",
    "              \"\\ncollage:\", self.__collage, \"\\nprofessional:\", self.__professional)\n",
    "\n",
    "    @property\n",
    "    def teachObj(self):\n",
    "        return '今天讲的如何面向对象设计程序'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p1 = Person(\"Quanwei\", \"18\", \"Male\")\n",
    "s1 = Student(\"Quanwei\", \"18\", \"Male\", \"电信学院\", \"软件2002\")\n",
    "s2 = Student(\"Dog\", \"18\", \"Male\", \"电信学院\", \"软件2002\")\n",
    "s3 = Student(\"Wangcai\", \"18\", \"Male\", \"电信学院\", \"软件2002\")\n",
    "t1 = Teacher(\"Zhou\", \"28\", \"Male\", \"电信学院\", \"Python\")\n",
    "p1.personInfo\n",
    "t1.personInfo\n",
    "s1.study(t1)\n",
    "for i in [s1, s2, s3]:\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"quanwei\".__len__()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 文件IO\n",
    "try:\n",
    "    f = open('../txts/hamlet.txt', 'r')\n",
    "    print(f.read())\n",
    "except:\n",
    "    print('ioerror')\n",
    "finally:\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 和前面的try ... finally是一样的\n",
    "# 并且不必调用f.close()方法\n",
    "with open('../txts/words.txt', 'r') as f:\n",
    "    print(f.read())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('../txts/words.txt', 'r') as f:\n",
    "    for line in f.readlines():\n",
    "        print(line)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from io import StringIO\n",
    "f = StringIO()\n",
    "f.write(\"Tang\")\n",
    "f.write(\" \")\n",
    "f.write(\"Quanwei\")\n",
    "print(f.getvalue())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "\n",
    "def fwrite():\n",
    "    with open('../txts/output.txt', 'a+', encoding='utf-8') as f:\n",
    "        f.write(time.ctime().center(40, '-')+'\\n' +\n",
    "                'Written by Quanwei.'.center(40)+'\\n')\n",
    "        cnt = 1\n",
    "        while s := input():\n",
    "            f.write(f'{cnt}. '+s+'\\n')\n",
    "            cnt += 1\n",
    "        nine_nine()\n",
    "        f.write('Cory Right 2021@ Quanwei'.center(41)+'\\n\\n')\n",
    "        f.seek(0)\n",
    "        print(f.read(), end='')\n",
    "\n",
    "\n",
    "def nine_nine():\n",
    "    with open('../txts/output.txt', 'a+', encoding='utf-8') as f:\n",
    "        for i in range(1, 10):\n",
    "            for j in range(1, i+1):\n",
    "                f.write(f'{j} * {i} = {i*j}\\t')\n",
    "            f.write('\\n')\n",
    "\n",
    "\n",
    "def fread():\n",
    "    with open('../txts/output.txt', 'r', encoding='utf-8') as f:\n",
    "        f.seek(0)\n",
    "        for line in f.readlines():\n",
    "            # print(line.strip(), end=['\\n', ''][line == '\\n'])  # 去除空行\n",
    "            print([line[::] for line in f.readlines() if line != '\\n'])\n",
    "\n",
    "\n",
    "fwrite()\n",
    "\n",
    "# nine_nine()\n",
    "# fread()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ls = []\n",
    "while s := input():  # while (s:=input())!='':\n",
    "    ls.append(s)\n",
    "ls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('../txts/user.txt', 'w+', encoding='utf-8') as f:\n",
    "    while (s := input('username:')+':'+input('password:')) != ':':\n",
    "        f.write(s+'\\n')\n",
    "\n",
    "# file will be save after f.close()\n",
    "with open('../txts/user.txt', 'r', encoding='utf-8') as f:\n",
    "    flag = 0\n",
    "    while True:\n",
    "        if flag in [0, 3]:\n",
    "            uname = input('Cheak Username:')\n",
    "        if flag in [0, 2]:\n",
    "            passwd = input('Cheak Passward:')\n",
    "        f.seek(0)\n",
    "        for line in f.readlines():\n",
    "            if uname == line[:line.find(':')]:\n",
    "                t = line[line.find(':')+1:-1]\n",
    "                if passwd == t:\n",
    "                    print(line, end='')\n",
    "                    flag = 1  # ok\n",
    "                    break\n",
    "                else:\n",
    "                    flag = 2\n",
    "                    break  # passwd error\n",
    "            else:\n",
    "                flag = 3  # uname error\n",
    "        if flag == 1:\n",
    "            print('OK')\n",
    "            break\n",
    "        print('Error! Again ', end='')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def init():\n",
    "    with open('../txts/user.txt', 'w+', encoding='utf-8') as f:\n",
    "        while (s := input('username:')+':'+input('password:')) != ':':\n",
    "            f.write(s+'\\n')\n",
    "\n",
    "\n",
    "def cheak():\n",
    "    # file will be save after f.close()\n",
    "    with open('../txts/user.txt', 'r', encoding='utf-8') as f:\n",
    "        flag = 0\n",
    "        while True:\n",
    "            if flag in [0, 3]:\n",
    "                uname = input('Cheak Username:')\n",
    "            if flag in [0, 2]:\n",
    "                passwd = input('Cheak Passward:')\n",
    "            f.seek(0)\n",
    "            for line in f.readlines():\n",
    "                if uname == line[:line.find(':')]:\n",
    "                    flag = [2, 1][passwd == line[line.find(':')+1:-1]]\n",
    "                    break\n",
    "                else:\n",
    "                    flag = 3\n",
    "            if flag == 1:\n",
    "                print('OK')\n",
    "                break\n",
    "            print('Error! Again ', end='')\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    init()\n",
    "    cheak()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('../txts/user.txt', 'r', encoding='utf-8') as f:\n",
    "    # cnt=1\n",
    "    # for line in f.readlines():\n",
    "    #     print(cnt,line.strip('\\n'))\n",
    "    #     cnt+=1\n",
    "    for i, j in enumerate(f, 1):\n",
    "        print(i, j.strip('\\n'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# add porcessed f1 to f2\n",
    "with open('../txts/user.txt', 'r', encoding='utf-8') as f1:\n",
    "    with open('../txts/user1.txt', 'w+', encoding='utf-8') as f2:\n",
    "        for line in f1.readlines():\n",
    "            f2.write(line.replace('f', 'F').replace('R', 'r'))\n",
    "        f2.seek(0)\n",
    "        print(f2.read())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.10.8 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  },
  "metadata": {
   "interpreter": {
    "hash": "ac59ebe37160ed0dfa835113d9b8498d9f09ceb179beaac4002f036b9467c963"
   }
  },
  "vscode": {
   "interpreter": {
    "hash": "e7370f93d1d0cde622a1f8e1c04877d8463912d04d973331ad4851f04de6915a"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
